package com.kum.service;

import com.alibaba.fastjson.JSON;
import com.kum.domain.dto.SysScriptDto;
import com.kum.domain.dto.SysUserScriptDto;
import com.kum.domain.entity.SysScript;
import com.kum.domain.entity.SysUserScript;
import com.kum.mapper.SysScriptMapper;
import com.kum.utils.RequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @version V1.0
 * @Package com.kum.service
 * @auhter 枯木Kum
 * @date 2021/6/16-10:24 AM
 * <p>...</p>
 */

@Service
public class SysScriptService {

    @Resource
    private SysScriptMapper scriptMapper;

    @Autowired
    private SysUserScriptService userScriptService;


    public List<SysUserScriptDto> get(String userId) {
        return scriptMapper.getMyScript(userId);

    }

    /**
     * 添加脚本
     *
     * @param scriptDto
     */
    public void add(SysScriptDto scriptDto) {
        //如果是油猴脚本，则直接对脚本内容解析
        if (scriptDto.isGreasyFork) {
            explainScript(scriptDto);
        }
        String currentLoginUserId = RequestUtils.getCurrentLoginUserId();
        scriptDto.setScriptAuthorId(currentLoginUserId);
        save(scriptDto);
        String scriptId = null;
        // 添加脚本与创建者关联数据
        if ((scriptId = scriptDto.getId()) != null) {
            SysUserScript userScript = new SysUserScript().toBuilder().userId(currentLoginUserId).scriptId(scriptId).build();
            userScriptService.save(userScript);
        }
    }

    public void save(SysScript script) {
        if (script.getId() != null) {
            scriptMapper.updateById(script);
        } else {
            scriptMapper.insert(script);
        }

    }

    public static SysScriptDto explainScript(SysScriptDto scriptDto) {
        String scriptText = scriptDto.getScriptText();
        int startIndex = scriptText.indexOf("// ==UserScript==") + 18;
        int endIndex = scriptText.indexOf("// ==/UserScript==");
        String scriptHead = scriptText.substring(startIndex, endIndex);
        String[] split = scriptHead.split("\n");
        String[] heads = {"// @name", "// @version", "// @icon",
                "// @description", "// @match", "// @require"};
        for (int i = 0; i < split.length; i++) {
            String headItem = split[i];
            if (headItem.contains("@name") && !headItem.contains("@namespace")) {
                String name = headItem.substring("// @name ".length()).trim();
                scriptDto.setScriptName(name);
            } else if (headItem.contains("// @version")) {
                scriptDto.setScriptVersion(headItem.substring("// @version".length()).trim());
            } else if (headItem.contains("// @icon")) {
                scriptDto.setScriptIcon(headItem.substring("// @icon".length()).trim());
            } else if (headItem.contains("// @description")) {
                scriptDto.setScriptDesc(headItem.substring("// @description".length()).trim());
            } else if (headItem.contains("// @match")) {
                scriptDto.getMatch().add(headItem.substring("// @match".length()).trim());
            } else if (headItem.contains("// @require")) {
                scriptDto.getRequire().add(headItem.substring("// @require".length()).trim());
            }
        }
        scriptDto.setScriptMatch(JSON.toJSONString(scriptDto.getMatch()));
        scriptDto.setScriptRequire(JSON.toJSONString(scriptDto.getRequire()));
        return scriptDto;

    }
}
